import pandas as pd
from sklearn.model_selection import train_test_split 
import lightgbm as lgb
from sklearn.metrics import mean_absolute_error, mean_squared_error
import matplotlib.pyplot as plt
#准备数据
df=pd.read_csv("H:\VS Code\深圳一手商品房数据处理\特征工程后数据集.csv")
df = df.astype({col: 'bool' for col in df.select_dtypes(include=['object']).columns})
x=df.drop(columns=['日期','季度','序号','用途_其他','月份','成交均价','过去1月均价'])#删除无关特征和占比极低的特征
y=df['成交均价']#目标变量
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,shuffle=False)#时间序列禁止随机打乱
X_train_encoded = pd.get_dummies(  
    x_train,  
    columns=['所属区'],  # 指定需编码的列  
    drop_first=True  # 避免多重共线性  
)  
#训练模型
params={
    'objective':'regression',
    'metric':'mae',
    'num_leaves':31,
    'learning_rate':0.05
}
model= lgb.LGBMRegressor(**params)

model.fit(x_train,y_train)
#预测
y_pred=model.predict(x_test)
print(y_pred[:20])#显示前十个预测值

#评估指标计算
mae = mean_absolute_error(y_test, y_pred)  
print(f"MAE: {mae:.0f} 元/㎡") 

#特征重要性分析
# LightGBM 特征重要性  
lgb.plot_importance(model, importance_type='gain', figsize=(10,6))  
plt.title('特征重要性（增益）')  
plt.show()
plt.savefig('feature_importance.png')  
